package com.atguigu;

/**
 * @author steve
 * @date 2025/08/19 17:38
 */
public class SynchronizedDemo {

    private int count = 0;

    // synchronized 方法，保证同一时间只有一个线程能执行
    public synchronized void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }

    public static void main(String[] args) throws InterruptedException {
        SynchronizedDemo demo = new SynchronizedDemo();

        // 创建两个线程同时操作同一个对象
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                demo.increment();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                demo.increment();
            }
        });

        t1.start();
        t2.start();

        // 等待线程执行完
        t1.join();
        t2.join();

        System.out.println("最终 count = " + demo.getCount());
    }
}
